package com.oa.ht.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.ht.entity.ContractCard;
import com.oa.ht.entity.ContractCondition;
import com.oa.ht.entity.ContractConditionBatchVo;
import com.oa.ht.service.ContractCardService;
import com.oa.ht.service.ContractConditionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/ht/contractCondition")
@Api(tags = {"ht_contract_condition-操作接口"})
public class ContractConditionController {

    static Logger logger = LoggerFactory.getLogger(ContractConditionController.class);

    @Autowired
    private ContractConditionService contractConditionService;
    @Autowired
    private ContractCardService contractCardService;

    @ApiOperation(value = "ht_contract_condition-查询列表", notes = " ")
    @ApiEntityParams(ContractCondition.class)
    @ApiResponses({@ApiResponse(code = 200, response = ContractCondition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listContractCondition(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "conditionIds");
        QueryWrapper<ContractCondition> qw = QueryTools.initQueryWrapper(ContractCondition.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = contractConditionService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ApiOperation(value = "批量新增修改合同首付款条件", notes = "batchSave")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchSave", method = RequestMethod.POST)
    public Result batchSave(@RequestBody ContractConditionBatchVo contractConditions) {
        if (!StringUtils.hasText(contractConditions.getHtId())) {
            return Result.error("htId-is-null", "合同编号不能为空");
        }
        ContractCard card = this.contractCardService.selectOneObject(new ContractCard(contractConditions.getHtId()));
        if (card == null) {
            return Result.error("ht-not-exists", "合同已不存在");
        }
        if ("1".equals(card.getHtStatus()) || "1".equals(card.getHtStatus()) || "2".equals(card.getHtStatus()) || "3".equals(card.getHtStatus()) || "6".equals(card.getHtStatus()) || "7".equals(card.getHtStatus())) {
            return Result.error("htStatus-not-right", "合同当前状态不允许修改收付款条件");
        }
        if (contractConditions.getContractConditions() != null && contractConditions.getContractConditions().size() > 0) {
            BigDecimal allConditionAmount = BigDecimal.ZERO;
            for (ContractCondition contractCondition : contractConditions.getContractConditions()) {
                allConditionAmount = allConditionAmount.add(contractCondition.getConditionAmount());
            }
            if (allConditionAmount.compareTo(card.getHtGrossAmount()) > 0) {
                return Result.error("htGrossAmount-not-right", "款项条件总金额不能大于合同总金额");
            }
        }
        contractConditionService.batchSave(contractConditions);
        return Result.ok("update-ok", "成功更新");
    }

    @ApiOperation(value = "ht_contract_condition-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractCondition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addContractCondition(@RequestBody ContractCondition contractCondition) {
        contractConditionService.save(contractCondition);
        return Result.ok("add-ok", "添加成功！");
    }

    @ApiOperation(value = "ht_contract_condition-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delContractCondition(@RequestBody ContractCondition contractCondition) {
        contractConditionService.removeById(contractCondition);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "ht_contract_condition-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractCondition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editContractCondition(@RequestBody ContractCondition contractCondition) {
        contractConditionService.updateById(contractCondition);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ApiOperation(value = "ht_contract_condition-批量修改某些字段", notes = "")
    @ApiEntityParams(value = ContractCondition.class, props = {}, remark = "ht_contract_condition", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = ContractCondition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        contractConditionService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "ht_contract_condition-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelContractCondition(@RequestBody List<ContractCondition> contractConditions) {
        User user = LoginUtils.getCurrentUserInfo();
        if (contractConditions.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<ContractCondition> datasDb = contractConditionService.listByIds(contractConditions.stream().map(i -> i.getConditionId()).collect(Collectors.toList()));

        List<ContractCondition> can = new ArrayList<>();
        List<ContractCondition> no = new ArrayList<>();
        for (ContractCondition data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            contractConditionService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getConditionId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "ht_contract_condition-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractCondition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(ContractCondition contractCondition) {
        ContractCondition data = (ContractCondition) contractConditionService.getById(contractCondition);
        return Result.ok().setData(data);
    }

}
